<template>
  <div>
    <Row>
      <Col span="24">
        <Card class="margin-bottom-10">
          <Form inline>
            <FormItem class="margin-bottom-0">
              <Select v-model="searchConf.status" clearable placeholder='请选择状态' style="width:120px">
                <Option :value="1">开发中</Option>
                <Option :value="2">维护中</Option>
                <Option :value="3">待下线</Option>
                <Option :value="4">已下线</Option>
              </Select>
            </FormItem>
            <FormItem class="margin-bottom-0">
              <Input v-model="searchConf.name" placeholder="游戏名称" />
            </FormItem>
            <FormItem class="margin-bottom-0">
              <Button type="primary" @click="search">{{ $t('find_button') }}/{{ $t('refresh_button') }}</Button>
            </FormItem>
          </Form>
        </Card>
      </Col>
    </Row>
    <Row>
      <Col span="24">
        <Card>
          <div class="margin-bottom-15">
            <Button type="primary" v-has="'GameList/add'" @click="alertAdd" icon="md-add">{{ $t('add_button') }}</Button>
            <Button type="warning" v-has="'GameVersion/publishServer'" icon="md-bulb" @click="alertPub" class="margin-left-5">发布</Button>
          </div>
          <div>
            <Table :loading="listLoading" :columns="columnsList" :data="tableData" border disabled-hover />
          </div>
          <div class="margin-top-15" style="text-align: center">
            <Page :total="tableShow.listCount" :current="tableShow.currentPage"
                  :page-size="tableShow.pageSize" @on-change="changePage"
                  @on-page-size-change="changeSize" show-elevator show-sizer show-total />
          </div>
        </Card>
      </Col>
    </Row>
    <Modal v-model="modalSetting.show" width="668" :styles="{top: '30px'}" @on-visible-change="doCancel">
      <p slot="header" style="color:#2d8cf0">
        <Icon type="md-alert" />
        <span>{{ formItem.id ? '编辑' : '新增' }}游戏</span>
      </p>
      <Form ref="myForm" :rules="ruleValidate" :model="formItem" :label-width="80">
        <FormItem label="游戏名称" prop="name">
          <Input v-model="formItem.name" placeholder="请输入游戏名称" />
        </FormItem>
        <FormItem label="游戏分类" prop="type">
          <Cascader :data="typeList" placeholder="请选择游戏分类" v-model="formItem.type" />
        </FormItem>
        <FormItem label="所属平台" prop="platform">
          <Select v-model="formItem.platform" placeholder="请选择所属平台" style="width:200px">
            <Option v-for="item in platformList" :value="item.id" :key="item.id">{{ item.title }}</Option>
          </Select>
        </FormItem>
        <FormItem label="游戏状态" prop="status">
          <Select v-model="formItem.status" clearable placeholder='请选择状态' style="width:200px">
            <Option :value="1">开发中</Option>
            <Option :value="2">维护中</Option>
            <Option :value="3">待下线</Option>
            <Option :value="4">已下线</Option>
          </Select>
        </FormItem>
        <FormItem label="AppId" prop="app_id">
          <Input v-model="formItem.app_id" placeholder="请输入AppId/AppKey" />
        </FormItem>
        <FormItem label="AppSecret" prop="app_secret">
          <Input v-model="formItem.app_secret" placeholder="请输入AppSecret" />
        </FormItem>
        <FormItem label="包名称" prop="app_name">
          <Input v-model="formItem.app_name" placeholder="请输入游戏包名称" />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="cancel" class="margin-right-10">取消</Button>
        <Button type="primary" @click="submit" :loading="modalSetting.loading">确定</Button>
      </div>
    </Modal>
    <Modal v-model="modalSetting.version" width="668" :styles="{top: '30px'}" @on-visible-change="doCancel">
      <p slot="header" style="color:#2d8cf0">
        <Icon type="md-alert" />
        <span>版本管理</span>
      </p>
      <div class="margin-bottom-15" v-has="'GameConfig/add'">
        <Input v-model="buildKeyInfo.version" placeholder="新版本号" class="margin-right-10" style="width: 200px" />
        <Button type="primary" @click="buildCdKeys" icon="md-add">{{ $t('add_button') }}</Button>
      </div>
      <div>
        <Table :columns="columnsVersion" :data="dataVersion" border disabled-hover />
      </div>
      <div slot="footer" style="text-align: center">
        <Page :total="keyShow.listCount" :current="keyShow.currentPage" :page-size="keyShow.pageSize"
              @on-change="changeKeyPage" @on-page-size-change="changeKeySize" show-elevator show-sizer show-total />
      </div>
      <div slot="footer">
        <Button type="text" @click="modalSetting.version = false" class="margin-right-10">取消</Button>
      </div>
    </Modal>
    <Modal v-model="modalSetting.pub" width="360">
      <p slot="header" style="color:#f60;text-align:center">
        <Icon type="ios-information-circle"></Icon>
        <span>发布确认</span>
      </p>
      <div style="text-align:center">
        <p>发布路由是一个非常危险的操作，确认执行么？</p>
      </div>
      <div slot="footer">
        <Button type="error" size="large" long @click="pubRoute">发布</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import { getList, add, edit, del } from '@/api/game-manager'
import { getChooseItem } from '@/api/game-type'
import { getChoose } from '@/api/game-platform'
import { getList as gvl, add as gva, changeStatus, publishServer } from '@/api/game-version'

const editButton = (vm, h, currentRow, index) => {
  if (vm.buttonShow.edit) {
    return h('Button', {
      props: {
        type: 'primary'
      },
      style: {
        margin: '0 5px'
      },
      on: {
        'click': () => {
          getChoose()
          vm.formItem.id = currentRow.id
          vm.formItem.name = currentRow.name
          vm.formItem.app_id = currentRow.app_id
          vm.formItem.app_secret = currentRow.app_secret
          vm.formItem.app_name = currentRow.app_name
          vm.formItem.platform = currentRow.platform
          vm.formItem.status = currentRow.status
          vm.formItem.type = vm.originType[currentRow.type].relation.split(',')
          vm.formItem.type = vm.formItem.type.map(function (data) {
            return +data
          })
          vm.formItem.type.push(currentRow.type)
          vm.modalSetting.show = true
          vm.modalSetting.index = index
        }
      }
    }, vm.$t('edit_button'))
  }
}
const deleteButton = (vm, h, currentRow, index) => {
  if (vm.buttonShow.del) {
    return h('Poptip', {
      props: {
        confirm: true,
        title: '您确定要删除这条数据吗? ',
        transfer: true
      },
      on: {
        'on-ok': () => {
          del(currentRow.id).then(response => {
            vm.tableData.splice(index, 1)
            vm.$Message.success(response.data.msg)
          })
          currentRow.loading = false
        }
      }
    }, [
      h('Button', {
        style: {
          margin: '0 5px'
        },
        props: {
          type: 'error',
          placement: 'top',
          loading: currentRow.isDeleting
        }
      }, vm.$t('delete_button'))
    ])
  }
}
const versionButton = (vm, h, currentRow, index) => {
  if (vm.buttonShow.version) {
    return h('Button', {
      props: {
        type: 'info'
      },
      style: {
        margin: '0 5px'
      },
      on: {
        'click': () => {
          vm.buildKeyInfo.game_hash = currentRow.hash
          vm.modalSetting.version = true
          vm.getKeyList()
        }
      }
    }, '版本管理')
  }
}

export default {
  name: 'game_list',
  data () {
    return {
      typeList: [],
      dataVersion: [],
      originType: {},
      columnsList: [
        {
          title: '序号',
          type: 'index',
          width: 65,
          align: 'center'
        },
        {
          title: '游戏名称',
          align: 'center',
          render: (h, params) => {
            return h('span', params.row.name + ' - ' + this.platformShow[params.row.platform])
          },
          minWidth: 120
        },
        {
          title: '唯一标识',
          align: 'center',
          key: 'hash',
          width: 360
        },
        {
          title: '游戏类型',
          align: 'center',
          width: 200,
          render: (h, params) => {
            let vm = this
            let sArr = []
            let t = vm.originType[params.row.type].relation.split(',')
            t.push(params.row.type)
            t.map(function (data) {
              let intData = parseInt(data)
              sArr.push(vm.originType[intData].title)
            })

            return h('span', sArr.join(' / '))
          }
        },
        {
          title: '状态',
          align: 'center',
          width: 100,
          render: (h, params) => {
            switch (params.row.status) {
              case 1:
                return h('Tag', {
                  attrs: {
                    color: 'primary'
                  }
                }, '开发中')
              case 2:
                return h('Tag', {
                  attrs: {
                    color: 'success'
                  }
                }, '维护中')
              case 3:
                return h('Tag', {
                  attrs: {
                    color: 'warning'
                  }
                }, '待下线')
              case 4:
                return h('Tag', {
                  attrs: {
                    color: 'error'
                  }
                }, '已下线')
            }
          }
        },
        {
          title: '操作',
          align: 'center',
          width: 280,
          render: (h, params) => {
            return h('div', [
              versionButton(this, h, params.row, params.index),
              editButton(this, h, params.row, params.index),
              deleteButton(this, h, params.row, params.index)
            ])
          }
        }
      ],
      columnsVersion: [
        {
          title: '序号',
          type: 'index',
          width: 65,
          align: 'center'
        },
        {
          title: '版本号',
          align: 'center',
          key: 'version',
          minWidth: 120
        },
        {
          title: '版本状态',
          align: 'center',
          render: (h, params) => {
            let opArr = []
            for (let key in this.serverList) {
              opArr.push(
                h('Option', {
                  props: {
                    key: key,
                    value: key
                  }
                }, this.serverList[key].name)
              )
            }

            return h('Select', {
              props: {
                value: params.row.status.toString(),
                transfer: true
              },
              on: {
                'on-change': (v) => {
                  if (v) {
                    changeStatus({
                      id: params.row.id,
                      status: v
                    })
                  }
                }
              }
            }, opArr)
          }
        }
      ],
      platformList: [],
      tableData: [],
      groupList: [],
      tableShow: {
        currentPage: 1,
        pageSize: 10,
        listCount: 0
      },
      searchConf: {
        name: '',
        status: ''
      },
      modalSetting: {
        show: false,
        pub: false,
        loading: false,
        version: false,
        index: 0
      },
      formItem: {
        name: '',
        platform: 0,
        app_id: '',
        app_secret: '',
        status: 1,
        app_name: '',
        type: [],
        id: 0
      },
      platformShow: {},
      ruleValidate: {
        name: [
          { required: true, message: '游戏名称不能为空', trigger: 'blur' }
        ],
        type: [
          { type: 'array', required: true, message: '请选择游戏分类', trigger: 'blur' }
        ]
      },
      buttonShow: {
        edit: true,
        del: true,
        version: true,
        changeStatus: true
      },
      listLoading: false,
      keyShow: {
        currentPage: 1,
        pageSize: 10,
        listCount: 0
      },
      serverList: {},
      buildKeyInfo: {
        version: '',
        game_hash: ''
      }
    }
  },
  created () {
    let vm = this
    vm.getList()
    vm.hasRule('GameList/edit').then(res => {
      vm.buttonShow.edit = res
    })
    vm.hasRule('GameList/del').then(res => {
      vm.buttonShow.del = res
    })
    vm.hasRule('GameConfig/index').then(res => {
      vm.buttonShow.version = res
    })
    vm.hasRule('GameList/changeStatus').then(res => {
      vm.buttonShow.changeStatus = res
    })
  },
  methods: {
    alertAdd () {
      this.modalSetting.show = true
    },
    getKeyList () {
      let vm = this
      gvl({
        page: vm.keyShow.currentPage,
        size: vm.keyShow.pageSize,
        game_hash: vm.buildKeyInfo.game_hash
      }).then(response => {
        vm.dataVersion = response.data.data.list
        vm.serverList = response.data.data.serverList
        vm.keyShow.listCount = response.data.data.count
      })
    },
    buildCdKeys () {
      let vm = this
      if (vm.buildKeyInfo.version) {
        gva(vm.buildKeyInfo).then(response => {
          vm.buildKeyInfo.version = ''
          vm.getKeyList()
        })
      }
    },
    alertPub () {
      this.modalSetting.pub = true
    },
    pubRoute () {
      publishServer().then(response => {
        this.$Message.success(response.data.msg)
        this.modalSetting.pub = false
      })
    },

    changeKeyPage (page) {
      this.keyShow.currentPage = page
      this.getKeyList()
    },
    changeKeySize (size) {
      this.keyShow.pageSize = size
      this.getKeyList()
    },
    submit () {
      let vm = this
      this.$refs['myForm'].validate((valid) => {
        if (valid) {
          vm.modalSetting.loading = true
          if (vm.formItem.id === 0) {
            add(vm.formItem).then(response => {
              vm.$Message.success(response.data.msg)
              vm.getList()
              vm.cancel()
            }).catch(() => {
              vm.modalSetting.loading = false
            })
          } else {
            edit(vm.formItem).then(response => {
              vm.$Message.success(response.data.msg)
              vm.getList()
              vm.cancel()
            }).catch(() => {
              vm.modalSetting.loading = false
            })
          }
        }
      })
    },
    cancel () {
      this.modalSetting.show = false
    },
    doCancel (data) {
      if (!data) {
        this.formItem.id = 0
        this.formItem.type = []
        this.formItem.app_id = ''
        this.formItem.app_secret = ''
        this.formItem.app_name = ''
        this.formItem.platform = 0
        this.$refs['myForm'].resetFields()
        this.modalSetting.loading = false
        this.modalSetting.index = 0
      }
    },
    changePage (page) {
      this.tableShow.currentPage = page
      this.getList()
    },
    changeSize (size) {
      this.tableShow.pageSize = size
      this.getList()
    },
    search () {
      this.tableShow.currentPage = 1
      this.getList()
    },
    getList () {
      let vm = this
      let params = {
        page: vm.tableShow.currentPage,
        size: vm.tableShow.pageSize,
        ...vm.searchConf
      }
      vm.listLoading = true
      getChooseItem().then(response => {
        vm.typeList = response.data.data.list
        vm.originType = response.data.data.origin
        getChoose().then(chooseRes => {
          vm.platformList = chooseRes.data.data.list
          vm.platformList.forEach(item => {
            vm.platformShow[item.id] = item.title
          })
          getList(params).then(listResponse => {
            vm.tableData = listResponse.data.data.list
            vm.tableShow.listCount = listResponse.data.data.count
            vm.listLoading = false
          })
        })
      })
    }
  }
}
</script>
